package com.app.filter;

import com.app.SpringAnnotationDef;
import com.app.model.ORG_UserInfo;
import com.app.model.User;
import com.app.service.admin.UserService;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: cnprinces
 * Date: 13-1-22
 * Time: 下午3:57
 * To change this template use File | Settings | File Templates.
 */
public class LoginFilter extends HttpServlet implements Filter {
    private static final Logger LOGGER = Logger.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) sRequest;
        HttpServletResponse response = (HttpServletResponse) sResponse;
        HttpSession session = request.getSession();
        String url = request.getServletPath();
        String contextPath = request.getContextPath();
        if (url.equals("")) url += "/";
        LOGGER.info(url);
        if ((url.startsWith("/") && !url.startsWith("/index.jsp") && !url.equals("/management.action") && !url.startsWith("/styles"))) {//若访问后台资源 过滤到login
            User currentUser = (User) session.getAttribute("loginedUser");
            if (currentUser == null) {//转入管理员登陆页面
              String msg=" {\"statusCode\":\"301\", \"message\":\"Session Timeout! Please re-sign in!\"}";
                if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || request.getParameter("ajax") != null) {
                    PrintWriter out = response.getWriter();
                    out.println(msg);
                } else {
                    /*response.sendRedirect(response.encodeRedirectURL(this.loginUrl + java.net.URLEncoder.encode(backToUrl, "UTF-8")));*/
                      response.sendRedirect(contextPath + "/index.jsp");
                }
                //  response.sendRedirect(contextPath + "/index.jsp");
                return;
            }

            /**
             *    @Resource(name = SpringAnnotationDef.USER_SERVICE)
            private UserService service;
             */
            WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
            UserService service = (UserService) cont.getBean(SpringAnnotationDef.USER_SERVICE);

            //修改用户的状态
            service.updateUserOnline(currentUser);

            //加载所有菜单的资源
            Map<String, String> map = (Map<String, String>) request.getSession().getServletContext().getAttribute("userSort");

            if (map == null) {
                LOGGER.info("开始加载所有的菜单缓存");
                map = service.loadUserResourcesCache(currentUser);
                request.getSession().getServletContext().setAttribute("userSort", map);
            }

            LOGGER.info(currentUser.getEname());
        }
        filterChain.doFilter(sRequest, sResponse);
    }
}
